package snack;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

public class Snack {
	
	private Piece snackHead;
	private ArrayList<Piece> snackBody;
	
	private int speed = 15;
	private DIRECTION curdir = DIRECTION.D;
	private boolean up,down,left,right;
	
	enum DIRECTION {
		L,R,U,D
	}
	
	public Snack() {
		snackHead = new Piece(100, 100);
		snackBody = new ArrayList<Piece>();
		
		for(int i = 0;i < 2;i++) {
			snackBody.add(new Piece(200, 200));
		}
	}
	
	public void draw(Graphics g,Boolean isHead) {
		
		Graphics2D g2 = (Graphics2D) g;
		if(!isHead) {
			for(Piece body:snackBody) {
				Rectangle2D r2 = new Rectangle2D.Double(body.getX(), body.getY(), 15, 15);
				g2.setColor(Color.YELLOW);
				g2.fill(r2);
			}
		} else {
			Rectangle2D r2 = new Rectangle2D.Double(snackHead.getX(), snackHead.getY(), 15, 15);
			g2.setColor(Color.RED);
			g2.fill(r2);
			move();
		}
		
	}
	
	/*
	 * 蛇体的移动根据蛇身移动
	 * 第一节蛇身等于蛇头移动前的位置
	 * 第二节蛇身等于第一节蛇身移动前的位置
	 * 以此类推
	 */
	private void move() {
		
		int x = snackHead.getX();
		int y = snackHead.getY();
		
		int prex = x;
		int prey = y;
		
		if(curdir == DIRECTION.U) {
			y -= speed;
			snackHead.setY(y);
			prey += speed;
		}
		
		if(curdir == DIRECTION.D) {
			y += speed;
			snackHead.setY(y);
			prey -= speed;
		}
		
		if(curdir == DIRECTION.L) {
			x -= speed;
			snackHead.setX(x);
			prex += speed;
		}
		
		if(curdir == DIRECTION.R) {
			x += speed;
			snackHead.setX(x);
			prex -= speed;
		}
		
		for(Piece body:snackBody) {
			
			int tempX, tempY;
			
			tempX = body.getX();
			tempY = body.getY();
			
			body.setX(prex);
			body.setY(prey);
			
			prex = tempX;
			prey = tempY;
		}
	}
	
	/**
	 * 键盘按压事件
	 * @param e
	 */
	public void keyPress(KeyEvent e) {
		switch (e.getKeyCode()) {
		case KeyEvent.VK_UP:
			up = true;
			break;
			
		case KeyEvent.VK_DOWN:
			down = true;
			break;
			
		case KeyEvent.VK_LEFT:
			left = true;
			break;
			
		case KeyEvent.VK_RIGHT:
			right = true;
			break;
		}
		judgeDir();
	}
	
	/**
	 * 判断方向
	 */
	private void judgeDir() {
		if (!left && !right && up && !down)
			curdir = DIRECTION.U;
		if (!left && !right && !up && down)
			curdir = DIRECTION.D;
		if (left && !right && !up && !down)
			curdir = DIRECTION.L;
		if (!left && right && !up && !down)
			curdir = DIRECTION.R;
	}
	
	/**
	 * 键盘抬起事件
	 * @param e
	 */
	public void keyRelease(KeyEvent e) {
		switch (e.getKeyCode()) {
		case KeyEvent.VK_UP:
			up = false;
			break;
			
		case KeyEvent.VK_DOWN:
			down = false;
			break;
			
		case KeyEvent.VK_LEFT:
			left = false;
			break;
			
		case KeyEvent.VK_RIGHT:
			right = false;
			break;
		}
	}
}
